package com.minelx.tableui.common;

import com.minelx.landisk.filesystem.Paths;
import com.minelx.landisk.filesystem.core.Directory;
import com.minelx.landisk.filesystem.core.init.OpenPolicy;
import com.minelx.tableui.form.PreviewForm;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.nio.charset.Charset;

import static com.minelx.landisk.filesystem.core.init.OpenPolicy.createANewOne;
import static com.minelx.landisk.filesystem.core.init.OpenPolicy.useExisting;

public class Chooser {
	public static com.minelx.landisk.filesystem.core.File openFile(Window owner, Directory root) {
		JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(new File(root.path().getAbsolutePath()));
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int option = chooser.showOpenDialog(owner);
		if (option != JFileChooser.APPROVE_OPTION) {
			throw new UnsupportedOperationException("user canceled.");
		}
		return Paths.of(chooser.getSelectedFile().getAbsolutePath(), useExisting());
	}

	public static com.minelx.landisk.filesystem.core.File saveFile(Window owner, Directory root) {
		JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(new File(root.path().getAbsolutePath()));
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int option = chooser.showSaveDialog(owner);
		if (option != JFileChooser.APPROVE_OPTION) {
			throw new UnsupportedOperationException("user canceled.");
		}
		String selectedFilePath = chooser.getSelectedFile().getAbsolutePath().replace("\\", "/");
		return Paths.of(selectedFilePath, createANewOne());
	}

	public static Charset chooseCharset() {
		String charsetName = (String) JOptionPane.showInputDialog(null,
				"文件编码:",
				"输入文件编码",
				JOptionPane.QUESTION_MESSAGE,
				null,
				new String[]{"UTF-8", "GB18030", "GBK"},
				"UTF-8");
		return Charset.forName(charsetName);
	}
}
